package edu.gatech.cs2340.tigershroud;

//necessary imports
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.TimePicker;

/** DateTimeActivity allows the user to select a date and time upon task creation. 
 * DateTimeActivity then saves the results to the database
 * @author [InsertNameHere]
 * @version 9.0x, Build April 3, 2012.
 */
public class DateTimeActivity extends Activity
{
	//instance variables
	private TodoDataSource ds;
	private Button create, cancel, date, time, back;
	private DatePicker dp;
	private TimePicker tp;
	private String d, t, tname, des, cat, addr, city, state, zip, stat, df, tf, dntf;
	private long dnum;
	private Intent intent;
	
	/**
	 * The onCreate method is a default android method that is called when the
	 * activity is first started. This onCreate method assigns passed objects to variables,
	 * sets up the DatePicker and TimePicker, opens the database, determines the layout of
	 * the activity, and sets listeners for items within the activity
	 * @param saveInstanceState the Bundle name value pair that represents the state of the object
	 *
	 */
    public void onCreate(Bundle savedInstanceState) 
    {
    	//override the super class
        super.onCreate(savedInstanceState);
        
        //set the layout using the datetme.xml file
        setContentView(R.layout.datetime);
        
        Log.d("DATE -- beginning of date", "inside date time activity");
        
        //initialize reference to the database
        ds = new TodoDataSource(this);
        
        //open the database
        ds.open();
        
        /*Instance variables that were created above 
        are initialized with the values from R.java*/
        
        date = (Button) findViewById(R.id.bdate);
        time = (Button) findViewById(R.id.btime);
        create = (Button) findViewById(R.id.bcreatetask);
        cancel = (Button) findViewById(R.id.bcanceltask2);
        back = (Button) findViewById(R.id.bback);
        
        dp = (DatePicker) findViewById(R.id.dpdate);
        tp = (TimePicker) findViewById(R.id.tptime);
        
        /*Get any/all fields from the previous activity
        Since the previous Activity was TaskActivity,
        all fields that were filled with user input are passed*/
        tname = getIntent().getExtras().getString("tname");
        des = getIntent().getExtras().getString("des");
        cat = getIntent().getExtras().getString("cat");
        addr = getIntent().getExtras().getString("addr");
        city = getIntent().getExtras().getString("city");
        state = getIntent().getExtras().getString("state");
        zip = getIntent().getExtras().getString("zip");
        d = getIntent().getExtras().getString("date");
        t = getIntent().getExtras().getString("time");
        dntf = getIntent().getExtras().getString("dnum");
        df = "";
        tf = "";
        
        //start a new intent
		intent = new Intent();
        
        /*DATETIME - format: YYYY-MM-DD HH:MM:SS
         * Set the dateButton's behavior withing the activity
         */
        date.setOnClickListener(new View.OnClickListener() 
        {
        	/**
        	 * This method inside the anonymous inner-class OnItemClickListener
        	 * determines the behavior of the application when the item is clicked.
        	 * When the item is clicked, the input from a DatePicker is recorded and formatted
        	 * @param v the View that is generated by the parent activity
        	 */
        	public void onClick(View v) 
        	{
        		//from the datepicker get the month date and year
        		d = dp.getYear() + "-" + (dp.getMonth()+1) + "-" + dp.getDayOfMonth();
        		df = checkDate(dp.getYear(), (dp.getMonth()+1), dp.getDayOfMonth());
        		Log.d("DATE", d);
        		Log.d("DATE", df);
        	}
        });
        
        /*DATETIME - format: YYYY-MM-DD HH:MM:SS
         * set the time Button's behavior within the Activity
         */
        time.setOnClickListener(new View.OnClickListener() 
        {
        	/**
        	 * This method inside the anonymous inner-class OnItemClickListener
        	 * determines the behavior of the application when the item is clicked.
        	 * When the item is clicked, the input from a TimePicker is recorded and formatted
        	 * @param v the View that is generated by the parent activity
        	 */
        	public void onClick(View v) 
        	{
        		//get the hour 
        		t = tp.getCurrentHour() + ":" + tp.getCurrentMinute() + ":00";
        		tf = checkTime(tp.getCurrentHour(), tp.getCurrentMinute(), "00");
        		Log.d("DATE", t);
        		Log.d("DATE", tf);
        	}
        });
        
        //set the behavior for create Button
        create.setOnClickListener(new View.OnClickListener() 
        {
        	/**
        	 * This method inside the anonymous inner-class OnItemClickListener
        	 * determines the behavior of the application when the item is clicked.
        	 * When the item is clicked, the user's input is checked for validity.
        	 * If the input is valid, the task is added to the database. If not, the invalid
        	 * values are replaced with default values.
        	 * @param v the View that is generated by the parent activity
        	 */
        	public void onClick(View v) 
        	{
        		//If the user entered time but not a date, set the date to current date
        		Task task = (Task)getIntent().getSerializableExtra("task");
        		if(d.equals("") && !t.equals(""))
        		{
        			d = dp.getYear() + "-" + (dp.getMonth()+1) + "-" + dp.getDayOfMonth();
        			df = checkDate(dp.getYear(), (dp.getMonth()+1), dp.getDayOfMonth());
           			dntf = df + tf;
        			dnum = Long.parseLong(dntf);
        			Log.d("DATE", "dnum: " + dnum);
        		}
        		//If the user entered a date but not a time, set the time to the current time
        		else if(t.equals("") && !d.equals(""))
        		{
        			t = tp.getCurrentHour() + ":" + tp.getCurrentMinute() + ":00";
        			tf = checkTime(tp.getCurrentHour(), tp.getCurrentMinute(), "00");
        			dntf = df + tf;
        			dnum = Long.parseLong(dntf);
        			Log.d("DATE", "dnum: " + dnum);
        		}
        		//If the user enters neither date or time, default to current time and day
        		else if(t.equals("") && d.equals(""))
        		{
        			d = dp.getYear() + "-" + (dp.getMonth()+1) + "-" + dp.getDayOfMonth();
        			t = tp.getCurrentHour() + ":" + tp.getCurrentMinute() + ":00";

        			df = checkDate(dp.getYear(), (dp.getMonth()+1), dp.getDayOfMonth());
        			tf = checkTime(tp.getCurrentHour(), tp.getCurrentMinute(), "00");
        			dntf = df + tf;
        			dnum = Long.parseLong(dntf);
        			Log.d("DATE", "dnum: " + dnum);
        		}
        		
        		
 //!!! What does this check for?       		
        		if(task != null)
        		{	
        			ds.editTaskName(task, tname);
        			task.setTaskName(tname);
        			ds.editDate(task, d);
        			task.setDate(d);
        			ds.editTime(task, t);
        			task.setTime(t);
        			ds.editDnum(task, dnum);
        			task.setDnum(dnum);
        			ds.editDescription(task, des);
        			task.setDescription(des);
        			ds.editCategory(task, cat);
        			task.setCategory(cat);
        			ds.editAddress(task, addr);
        			task.setAddress(addr);
        			ds.editCity(task, city);
        			task.setCity(city);
        			ds.editState(task, state);
        			task.setState(state);
        			ds.editZipCode(task, zip);
        			task.setZipCode(zip);
        		}
        		else
        		{	
        			Log.d("DATE", "dnum: " + dnum);
	        		ds.createTask(tname, d, t, dnum, des, cat, addr, city, state, zip, "0");
        		}
        		//close database
        		ds.close();
        		
        		intent.putExtra("back", "create");
        		setResult(RESULT_OK, intent);
        		
        		//finish the activity
        		finish();
        	}
        });
       
        //set the behavior for cancel button in Activity
        cancel.setOnClickListener(new View.OnClickListener() 
        {
        	/**
        	 * This method inside the anonymous inner-class OnItemClickListener
        	 * determines the behavior of the application when the item is clicked.
        	 * When the item is clicked, the user returns to the previous screen. The current activity closes
        	 * @param v the View that is generated by the parent activity
        	 */
        	
			public void onClick(View v) 
			{
				ds.close();
        		intent.putExtra("back", "cancel");
        		setResult(RESULT_OK, intent);
				finish();
			}
		});
        
        //set behaviro for back button
        back.setOnClickListener(new View.OnClickListener() 
        {
        	/**
        	 * This method inside the anonymous inner-class OnItemClickListener
        	 * determines the behavior of the application when the item is clicked.
        	 * When the item is clicked, the user returns to the previous screen,
        	 * values that were previously entered are displayed
        	 * @param v the View that is generated by the parent activity
        	 */
			public void onClick(View v) 
			{
				//close database
				ds.close();
				
				//pass fields to previous activity
		        intent.putExtra("tname", tname);
				intent.putExtra("des", des);
				intent.putExtra("cat", cat);
				intent.putExtra("addr", addr);
				intent.putExtra("city", city);
				intent.putExtra("state", state);
				intent.putExtra("zip", zip);
				intent.putExtra("date", d);
				intent.putExtra("time", t);
				intent.putExtra("dnum", dntf);
				intent.putExtra("back", "back");
	
				setResult(RESULT_OK, intent);
				
				//end activity
				finish();
			}
		});
    }
    /**
	 * This method checks to see if the month, day, and year are valid and fall within a certain range.
	 * If the input is valid, a formatted String representing month, day, and year is returned
	 * values are replaced with default values.
	 * @param y a specified year
	 * @param m a specified month
	 * @param d a specified day
	 */
    public String checkDate(int y, int m, int d)
    {
		if(m < 10 && d > 9)
		{
			df = y + "0" + m + "" + d;
		}
		else if(d < 10 && m > 9)
		{
			df = y + "" + m + "0" + d;
		}
		else if(d < 10 && m < 10)
		{
			df = y + "0" + m + "0" + d;
		}
		else if(m > 9 && d > 9)
		{
			df = y + "" + m + "" + d;
		}
		return df;
    }
    /**
   	 * This method checks to see if the hour, minute, and seconds are valid and fall within a certain range.
   	 * If the input is valid, a formatted String representing hour, minute, and seconds is returned
   	 * values are replaced with default values. Time is expressed in military time.
   	 * @param h a specified hour of the day
   	 * @param m a specified number of minutes
   	 * @param s a specified number of seconds
   	 */  
    public String checkTime(int h, int m, String s)
    {
    	if(h < 10 && m > 9)
		{
    	    tf = "0" + h + "" + m + "" + s;
		}
    	else if(m < 10 && h > 9)
		{
     	    tf = h + "0" + m + "" + s;
		}
    	else if(m < 10 && h < 10)
		{
			tf = "0" + h + "0" + m + "" + s;
		}
    	else if(m > 9 && h > 9)
		{
			tf = h + "" + m + "" + s;
		}
		return tf;
    }
}
